package com.ocom.payhandle.runable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ocom.common.AcpService;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.pay.EntityAbnormal;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.simple.GzhMsgRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.JsonUtils;
import com.ocom.common.vo.pay.ServiceChargesVo;
import com.ocom.payhandle.feign.MqSimpleFeign;
import com.ocom.payhandle.feign.UgcapiFeign;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import com.ocom.redis.util.RedisUtil;
import org.slf4j.Logger;

import java.util.List;


public class OrderRunnableTask implements Runnable {


    private XfRecordProcessExxxService xfRecordProcessExxxService;
//    private XfRecordProcessService xfRecordProcessService;

    private XfGoodsListProcessService xfGoodsListProcessService;

    private XfRecordFeign xfRecordFeign;

    private XfMerchPayInfoService xfMerchPayInfoService;

    private UgcapiFeign ugcapiFeign;

    AbnormalService abnormalService;

    private XfAccountTypeService xfAccountTypeService;

    private CompanyConfigService companyConfigService;

    private RedisUtil redisUtil;

    private MqSimpleFeign mqSimpleFeign;

    public Logger log ;

    private MqSaveOrderVo mqSaveOrderVo;

    public OrderRunnableTask(
            XfRecordProcessExxxService xfRecordProcessExxxService,
//            XfRecordProcessService xfRecordProcessService,
            XfGoodsListProcessService xfGoodsListProcessService,
            XfRecordFeign xfRecordFeign,
            XfMerchPayInfoService xfMerchPayInfoService,
            UgcapiFeign ugcapiFeign,
            AbnormalService abnormalService,
            XfAccountTypeService xfAccountTypeService,
            CompanyConfigService companyConfigService,
            RedisUtil redisUtil,
            MqSimpleFeign mqSimpleFeign,
            Logger log,
            MqSaveOrderVo mqSaveOrderVo
    ) {
        this.xfRecordProcessExxxService= xfRecordProcessExxxService;
//        this.xfRecordProcessService = xfRecordProcessService;
        this.xfGoodsListProcessService = xfGoodsListProcessService;
        this.xfRecordFeign = xfRecordFeign;
        this.xfMerchPayInfoService = xfMerchPayInfoService;
        this.ugcapiFeign = ugcapiFeign;
        this.abnormalService = abnormalService;
        this.xfAccountTypeService = xfAccountTypeService;
        this.companyConfigService = companyConfigService;
        this.redisUtil = redisUtil;
        this.mqSimpleFeign = mqSimpleFeign;
        this.log = log;
        this.mqSaveOrderVo = mqSaveOrderVo;

    }

    @Override
    public void run() {

        try {
//            log.info("SavrOrderMqListener_queue 消费中");

//            log.info("消费数据 【{}】 【mq优先级】 【{}】 ",mqSaveOrderVo,mqSaveOrderVo.getComId());

            if(mqSaveOrderVo.getId() == null ){
                log.info("SavrOrderMqListener_queue id 空 手动签收消息,通知mq服务器端删除该消息");
                return;
            }


            //TODO 数据库操作样例
            log.info("SavrOrderMqListener-start Tg8C5yHy :【{}】【{}】【{}】",mqSaveOrderVo.getComId(),mqSaveOrderVo.getId(),mqSaveOrderVo);
//            log.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());

            try {

                EntityXfRecordProcessExxx entityXfRecordProcess = null;

                if (!CommonUtil.isNull(mqSaveOrderVo.getRedisOrderNo())) {
                    entityXfRecordProcess = JsonUtils.fromJson(redisUtil.get(mqSaveOrderVo.getRedisOrderNo()), EntityXfRecordProcessExxx.class);
                }
                if (entityXfRecordProcess == null) {
                    entityXfRecordProcess = xfRecordProcessExxxService.selectTradeNo(mqSaveOrderVo.getComId(), mqSaveOrderVo.getId());
                }

                if(entityXfRecordProcess == null){
                    EntityAbnormal entityAbnormal=new EntityAbnormal();
                    entityAbnormal.setComId(mqSaveOrderVo.getComId());
                    entityAbnormal.setPlatOrderNo(mqSaveOrderVo.getId().toString());
                    entityAbnormal.setType(2);
                    entityAbnormal.setRemark("线程池迁移失败");
                    abnormalService.Add(mqSaveOrderVo.getComId(),entityAbnormal);

                    log.error("线程池迁移订单报错 m5RTZgVw  【{}】 【{}】",mqSaveOrderVo.getRedisOrderNo(),mqSaveOrderVo);
                    return;
                }

                EntityXfRecord entityXfRecord = JSONObject.parseObject(JSON.toJSONString(entityXfRecordProcess),EntityXfRecord.class);

//                log.info("异步迁移订单 ejLK2gSc :entityXfRecordProcess【{}】 entityXfRecord【{}】",entityXfRecordProcess,entityXfRecord);

                Result result= null;
                if(mqSaveOrderVo.getType()<3){
                    if(mqSaveOrderVo.getType()!=2){   //2 仅迁移
                        entityXfRecord.setPayState(1);
                    }
                    result = xfRecordFeign.sveXfRecord(entityXfRecord);
                }else if (mqSaveOrderVo.getType() == 3){ //更新
                    entityXfRecord.setConsState(5);
                    result = xfRecordFeign.updateXfRecord(entityXfRecord);
                }

//			//查订单
                if(entityXfRecord.getConsType()==100 || entityXfRecord.getConsState()==3 || entityXfRecord.getConsState()==5 || entityXfRecord.getConsState()==205){
                    try {
                        List<EntityXfGoodsListProcess> listProcesses = null;

                        if (!CommonUtil.isNull(mqSaveOrderVo.getRedisOrderNo())) {
                            listProcesses = JsonUtils.fromJson((String) redisUtil.get(mqSaveOrderVo.getRedisOrderNo() + ":GOOD"), new TypeReference<List<EntityXfGoodsListProcess>>() {
                            });
                        }
                        if (listProcesses == null) {
                            listProcesses = xfGoodsListProcessService.getXfGoodsList(entityXfRecord.getComId(), entityXfRecord.getOrderNo());
                        }
                        if (listProcesses == null) {
                            log.error("线程池迁移菜品报错 m5RTZgVw  【{}】 【{}】", mqSaveOrderVo.getRedisOrderNo(), mqSaveOrderVo);
                            // return;
                        }

                        if(listProcesses!=null && listProcesses.size()>0){
                            List<EntityXfGoodListOrg> listOrgs =JSON.parseArray(JSON.toJSONString(listProcesses),EntityXfGoodListOrg.class);
                            if(mqSaveOrderVo.getType()<3) {
                                xfRecordFeign.saveXfGoodListBatch(listOrgs);
                            }else if (mqSaveOrderVo.getType() == 3 && entityXfRecord.getIfRefund()==1){
                                RefundOrderDishesRequest refundOrderDishesRequest =new RefundOrderDishesRequest();
                                refundOrderDishesRequest.setComId(entityXfRecordProcess.getComId());
                                refundOrderDishesRequest.setOrderNo(entityXfRecord.getOrderNo());
                                refundOrderDishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());
                                refundOrderDishesRequest.setRemark("菜品退款");
                                xfRecordFeign.refund(refundOrderDishesRequest);
                            }
                        }
                    } catch (Exception e) {
                        log.error("mq迁移菜品报错 wWTbjE8o  【{}】 【{}】【{}】",entityXfRecord.getOrderNo(),entityXfRecord,e);
                    }
                }

                EntityCompanyConfig hongBao = companyConfigService.getTapValue(entityXfRecordProcess.getComId(), "hongBao");

                if(entityXfRecord.getPayWay()==7
                        && (entityXfRecord.getOpTypeDiff() == 201l || entityXfRecord.getOpTypeDiff() == 202l
                        || (hongBao!=null &&  hongBao.getConfig().equals("true")) )){
                    String canKey  = "delayqueryFee#comId:" +entityXfRecord.getComId()+"#orderNo:"+entityXfRecord.getOrderNo();
                    Object ex = redisUtil.get(canKey);
                    if(ex==null){
                        //调用延迟mq
                        EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(entityXfRecord.getComId(),entityXfRecord.getPayChannelNo());
                        if(entiyXfMerchPayInfo!=null){
                            try {
                                ServiceChargesVo serviceChargesVo =new ServiceChargesVo();
                                serviceChargesVo.setCompanyId(entiyXfMerchPayInfo.getCompanyId());
                                serviceChargesVo.setUserName(entiyXfMerchPayInfo.getUserName());
                                serviceChargesVo.setPassword(entiyXfMerchPayInfo.getPassword());
                                serviceChargesVo.setMachNo("00000000");
                                serviceChargesVo.setComId(entityXfRecord.getComId());
                                serviceChargesVo.setTradeNo(entityXfRecord.getOrderNo());
                                ugcapiFeign.serviceCharges(serviceChargesVo);
                                redisUtil.set(canKey,canKey,180l);
                            }catch (Exception e){
                                log.info("查询费率异常 FcT3DSMb ,【{}】",mqSaveOrderVo);
                            }

                        }
                    }
                }


                try {
                    EntityCompanyConfig entityCompanyConfig = companyConfigService.getTapValue(entityXfRecordProcess.getComId(), "gzhMsg");
                    if (entityXfRecord.getPayState()==1 && entityCompanyConfig != null && entityCompanyConfig.getConfig().equals("true") && entityXfRecordProcess.getAccTypeId()>0) {
                        GzhMsgRequest gzhMsgRequest = new GzhMsgRequest();
                        gzhMsgRequest.setComId(entityXfRecordProcess.getComId());
                        gzhMsgRequest.setMerchId(entityXfRecordProcess.getMerchId());
                        gzhMsgRequest.setPId(entityXfRecordProcess.getPId());
                        gzhMsgRequest.setOrderNo(entityXfRecordProcess.getOrderNo());
                        gzhMsgRequest.setType(2);
                        gzhMsgRequest.getParams().setUserName(entityXfRecordProcess.getPName());
                        gzhMsgRequest.getParams().setPayTime(DateUtil.getDateTime(entityXfRecordProcess.getConsTime()));
                        gzhMsgRequest.getParams().setPayMoney(AcpService.stringAmount(entityXfRecordProcess.getConsMoney().toString()));
                        gzhMsgRequest.getParams().setBalance(AcpService.stringAmount(entityXfRecordProcess.getChargeBalance().toString()));
                        gzhMsgRequest.getParams().setPointName("饭堂");
                        if(!CommonUtil.isNull(entityXfRecordProcess.getPointName())){
                            gzhMsgRequest.getParams().setPointName(entityXfRecordProcess.getPointName());
                        }

                        gzhMsgRequest.getParams().setAccTypeName("");
                        EntityXfAccountType entityXfAccountType = xfAccountTypeService.getXFAccountType(entityXfRecordProcess.getComId(), entityXfRecordProcess.getAccTypeId());
                        if (entityXfAccountType != null) {
                            gzhMsgRequest.getParams().setAccTypeName(entityXfAccountType.getAccTypeName());
                        }
                        mqSimpleFeign.gzhMsg(gzhMsgRequest);
                    }
                } catch (Exception exception) {
                    log.info("公众号消息发送失败 mcaXeS7h :{{}}", exception.getMessage());
                }

//                log.info("异步迁移订单: result【{}】",result);
                if (result == null || (result.getCode()!=200 &&  result.getCode()!=802)){
                    EntityAbnormal entityAbnormal=new EntityAbnormal();
                    entityAbnormal.setComId(mqSaveOrderVo.getComId());
                    entityAbnormal.setPlatOrderNo(mqSaveOrderVo.getId().toString());
                    entityAbnormal.setType(2);
                    entityAbnormal.setRemark("mq迁移失败");
                    abnormalService.Add(mqSaveOrderVo.getComId(),entityAbnormal);

                    log.error("Task迁移成功库失败 wa64zvlq  【{}】 【{}】【{}】",entityXfRecord.getOrderNo(),entityXfRecord,result);
                }else{
                    if(mqSaveOrderVo.getType()==1){
                        abnormalService.delAbnormal(mqSaveOrderVo.getComId(),mqSaveOrderVo.getId().toString());
                    }
                    // 手动签收消息,通知mq服务器端删除该消息
                    return;
                }
            } catch (Exception e) {
                log.info("mq消息处理失败 2YknR2fh :【{}】【{}】",mqSaveOrderVo,e);
            }
        } catch (Exception exception) {
            log.info("订单线程池迁移异常 z2TtMU3Y :【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "线程池迁移", mqSaveOrderVo.getMachNo(), mqSaveOrderVo, exception);
        }

    }
}
